<template>
  <!-- viewer.properties: 该文件为PDF插件的中文版配置，放置本地或使用服务器网络地址 -->
  <link rel="resource" type="application/l10n" href="/src/assets/files/viewer.properties" />
  <VuePdfApp
    class="toolbar"
    :page-scale="pageScale"
    :theme="theme"
    :style="`width: ${viewerWidth}; height: ${viewerHeight};`"
    :pdf="src"
    :file-name="fileName"
    v-bind="$attrs"
    @pages-rendered="pagesRendered"
    :config="config"
  >
    <template #toolbar-middle-append="{ toggleTheme }">
      <div>
        <el-cascader
          v-model="Cascader_value"
          :options="options"
          :show-all-levels="false"
          filterable
          @change="handleChange"
          @click="toggleTheme"
        />
      </div>
    </template>
  </VuePdfApp>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import VuePdfApp from "vue3-pdf-app";
import "vue3-pdf-app/dist/icons/main.css"; // 引入样式
import { DownloadFile, GetPDFFolder } from "@/api/modules/upload";

const Cascader_value = ref([]);
const src = ref("");
const options = ref<any>([]);

// 工具栏配置项
const config = ref({
  // 右侧其他区工具
  sidebar: {
    viewThumbnail: true, //启用缩略图视图
    viewOutline: true, //启用大纲视图
    viewAttachments: false //启用附件视图
  },
  secondaryToolbar: {
    secondaryPresentationMode: true, //启用演示模式
    secondaryOpenFile: true, //启用打开文件功能
    secondaryPrint: true, //启用打印功能
    secondaryDownload: true, //启用下载功能
    secondaryViewBookmark: true, //启用书签视图
    firstPage: true, //启用跳转到第一页
    lastPage: true, //启用跳转到最后一页
    pageRotateCw: true, //启用顺时针旋转页面
    pageRotateCcw: true, //启用逆时针旋转页面
    cursorSelectTool: true, //启用选择工具
    cursorHandTool: true, //启用手形工具
    scrollVertical: true, //启用垂直滚动
    scrollHorizontal: true, //启用水平滚动
    scrollWrapped: true, //启用包裹滚动
    spreadNone: true, //启用无跨页模式
    spreadOdd: true, // 启用奇数页跨页模式
    spreadEven: true, //启用偶数页跨页模式
    documentProperties: true //启用文档属性查看
  },
  // 配置左侧工具栏
  toolbar: {
    toolbarViewerLeft: {
      findbar: true, //启用查找条
      previous: true, // 启用上一页按钮
      next: true, //启用下一页按钮
      pageNumber: true // 启用页码显示
    },
    //  配置右侧工具栏
    toolbarViewerRight: {
      presentationMode: true, //启用演示模式
      openFile: true, //启用打开文件功能
      print: true, //启用打印功能
      download: true, // 启用下载功能
      viewBookmark: false // 启用书签视图
    },
    // 配置中间工具栏
    toolbarViewerMiddle: {
      zoomOut: true, // 启用缩小功能
      zoomIn: true, //启用放大功能。
      scaleSelectContainer: true //启用缩放选择容器功能
    }
  },
  errorWrapper: true //启用错误包装，这可能用于显示错误信息或处理错误情况。
});

const handleChange = async (value: any) => {
  const new_result = findPathByValues(options.value, value);
  await fetchSetValue(new_result?.path);
};

interface Props {
  //src: string; // pdf地址
  width?: string | number; // 预览容器宽度
  height?: string | number; // 预览容器高度
  pageScale?: number | string; // 页面默认缩放规则，可选 'page-actual'|'page-width'|'page-height'|'page-fit'|'auto'
  theme?: string; // 预览主题 可选 dark | light
  fileName?: string; // 覆盖pdf文件名
  //options?: any;
}
const props = withDefaults(defineProps<Props>(), {
  //src: "",
  width: "100%",
  height: "100vh",
  pageScale: "page-fit", // 默认自适应展示一页
  theme: "light",
  fileName: ""
  //options: []
});

const viewerWidth = computed(() => {
  if (typeof props.width === "number") {
    return props.width + "px";
  } else {
    return props.width;
  }
});
const viewerHeight = computed(() => {
  if (typeof props.height === "number") {
    return props.height + "px";
  } else {
    return props.height;
  }
});

function findFirstPdf(data) {
  for (const item of data) {
    if (item.path.endsWith(".pdf")) {
      return { pathValues: collectValues(item), pdfPath: item.path };
    }
    if (item.children && item.children.length > 0) {
      const result = findFirstPdf(item.children);
      if (result) {
        return { pathValues: [item.value, ...result.pathValues], pdfPath: result.pdfPath };
      }
    }
  }
  return null;
}

function collectValues(item) {
  const values = [item.value];
  if (item.children) {
    for (const child of item.children) {
      values.push(...collectValues(child));
    }
  }
  return values;
}

function findPathByValues(data, values) {
  let currentLevel = data;
  for (const value of values) {
    let found = false;
    for (const item of currentLevel) {
      if (item.value === value) {
        if (value === values[values.length - 1]) {
          // 如果是最后一个值，返回路径
          return { path: item.path, node: item };
        } else {
          // 继续深入下一层
          currentLevel = item.children;
          found = true;
          break;
        }
      }
    }
    if (!found) {
      return null; // 如果在当前层没有找到匹配的值，则返回null
    }
  }
  return null; // 如果遍历完所有值也没有找到匹配的路径，则返回null
}

async function fetchSetValue(pdfPath) {
  const BOlb = await DownloadFile({ pathValue: pdfPath });
  src.value = URL.createObjectURL(BOlb as Blob);
}

async function fetchAndSetViewerProperties() {
  const res = await GetPDFFolder({ folder: "会议专栏" });
  options.value = res.data;
}

onMounted(async () => {
  await fetchAndSetViewerProperties();
  const result = findFirstPdf(options.value);
  Cascader_value.value = result.pathValues;
  await fetchSetValue(result.pdfPath);
});

const emit = defineEmits(["loaded"]);
// emitted when pdf document pages are rendered. Can be used to set default pages scale
function pagesRendered(pdfApp: any) {
  emit("loaded", pdfApp);
}
</script>

<style lang="scss" scoped>
.toolbar {
  z-index: 0;
}
:deep(.el-input__wrapper) {
  width: 400px;
  background: #6c757d;
  box-shadow: none;
}
:deep(.el-cascader:not(.is-disabled):hover .el-input__wrapper) {
  box-shadow: none;
}
:deep(.el-input__inner) {
  color: hsl(0deg 0% 100% / 87%);
  text-align: center;
}
</style>
